package edu.hnnu.sport_event.controller;

import edu.hnnu.sport_event.entity.User;
import edu.hnnu.sport_event.service.AdminService;
import edu.hnnu.sport_event.service.StudentService;
import edu.hnnu.sport_event.status.LoginStatus;
import edu.hnnu.sport_event.utils.Result;
import edu.hnnu.sport_event.utils.ValidationCode;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Objects;

@RestController
public class LoginController {

    private String code = null;

    @Resource
    AdminService adminService;

    @Resource
    StudentService studentService;

    // 管理员登录
    public int adminLogin(User user) {
        return adminService.login(user);
    }

    // 用户登录
    public int studentLogin(User user) {
        return studentService.login(user);
    }

    @RequestMapping("login")
    public Result login(User user, String number, Integer status, HttpServletResponse response) {

        if (!Objects.equals(number, code)) {
            return Result.error("验证码填写错误！", LoginStatus.STATUS_ERROR.code());
        }

        // 身份判断
        if (status == null) return Result.error("请选择用户身份");

        // 管理员还是学生？
        int res = status == 1 ? adminLogin(user) : studentLogin(user);

        if (res > 0) {
            Cookie id = new Cookie("id", String.valueOf(res));
            response.addCookie(id);
            return Result.success("登录成功", res);
        }
        if (res == -1) return Result.error("登录失败，密码错误", LoginStatus.PASSWORD_ERROR.code());
        if (res == -2) return Result.error("登录失败，该用户不存在", LoginStatus.USERNAME_ERROR.code());
        return Result.error("未知错误");
    }

    @RequestMapping("getCode")
    public void getCode(HttpServletResponse response) throws IOException {
        ServletOutputStream out = response.getOutputStream();
        code = ValidationCode.getValidationCode(out);
        out.close();
    }



}
